import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import 'styles/credit/credit-view/reimbursement-credit.scss'
import { Radio, Table, Input, Spin, Badge, Popover, Dropdown, Menu, Icon } from 'antd'
import SlideFrame from 'components/slide-frame'
import EventDetail from 'containers/credit-setting/credit-management/cancel-detail'
import creditViewService from 'containers/credit/credit-view/credit-view.service'
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const Search = Input.Search;
import constants from 'share/constants'
import moment from 'moment'
import debounce from 'lodash.debounce'
import Condition from 'components/condition'
const { If, Else } = Condition;
import ResizeTable from 'components/resize-table'

class ReimbursementCredit extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      columns: [{
        title: messages('credit.key2')/*员工*/, dataIndex: 'fullName'
      },{
        title: messages('credit.key3')/*相关单据*/, dataIndex: 'businessCode'
      },{
        title: messages('credit.key4')/*事件描述*/, dataIndex: 'comment'
      },{
        title: messages('credit.key5')/*信用规则*/, dataIndex: 'ruleCondition'
      },{
        title: messages('credit.key6')/*信用类型*/, dataIndex: 'modelTypeId', render: modelTypeId => messages('credit.key1')/*报销信用*/
      },{
        title: messages('credit.key7')/*处理方式*/, dataIndex: 'operationType', render: operationType => constants.getTextByValue(operationType, 'creditRuleOperation')
      },{
        title: messages('credit.key8')/*处理结果*/, dataIndex: 'changeRank', render: (text, record) =>
          `${record.operationType % 2 === 0 ? '-' : '+'}${record.operationType > 1002 ? record.changeRank : record.changeScore}`
      },{
        title: messages('credit.key9')/*更新时间*/, dataIndex: 'createdDate', render: value => value ? moment(value).format('YYYY-MM-DD') : '-'
      },{
        title: messages('credit.key10')/*处理人*/, dataIndex: 'operatorName'
      },{
        title: messages('common.column.status')/*状态*/, dataIndex: 'status', render: status => (
          <Badge status={status === 1001 ? 'success' : 'error'}
                 text={status === 1001 ? messages("common.status.enable") : messages('credit.key11')/*作废*/}/>)
      }],
      userLoading: false,
      tableLoading: false,
      userInfo: {},
      pagination: {
        total: 0
      },
      page: 0,
      size: 10,
      data: [],
      operationType: null,
      businessCode: '',
      showSlideFrame: false,
      nowData: {},
      isOneMorePost: false,
      jobList:[],
      jobListObj:{},
      selectedJob: null,
      jobId: null,
      departmentName: props.user.departmentName,
      companyName: props.user.companyName,
    };
    this.handleChangeBusinessCode = debounce(this.handleChangeBusinessCode, 250);
  }

  componentWillMount(){
    let { jobListObj } = this.state;

    creditViewService.getUserJobs(this.props.user.userOID).then(res=>{
      let data = res.data;
      if (data && data.userJobsDTOs) {
        // jobListObj
        data.userJobsDTOs.map(job => {
          jobListObj[job.id] = job;
        });
        this.setState({ isOneMorePost: !!data.userJobsDTOs.length, jobList: data.userJobsDTOs, jobListObj });
      }
    });
    this.getUser();
    this.getList();
  }

  getUser = () => {
    let { jobId } = this.state;
    this.setState({ userLoading: true });
    creditViewService.getUserCreditInfo({ jobId }).then(res => {
      this.setState({ userInfo: res.data, userLoading: false })
    });
  };

  getList = () => {
    const { operationType, page, size, businessCode, jobId } = this.state;
    const { user } = this.props;
    this.setState({ tableLoading: true });
    creditViewService.getUserCreditEvent({ page, size, operationType, businessCode, jobId }).then(res => {
      this.setState({
        tableLoading: false,
        data: res.data,
        pagination: {
          total: Number(res.headers['x-total-count']),
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    })
  };

  onChangePager = (page) => {
    if(page - 1 !== this.state.page)
      this.setState({ page: page - 1 }, this.getList)
  };

  handleChangeRadio = e => {
    this.setState({ operationType: e.target.value, page: 0 }, this.getList)
  };

  handleChangeBusinessCode = businessCode => {
    this.setState({ businessCode, page: 0 }, this.getList)
  };

  rowClick = record => {
    this.setState({ nowData: record, showSlideFrame: true });
  };

  joinJob = item => {
    let res = [];
    item.position && res.push(item.position);
    item.companyName && res.push(item.companyName);
    item.departmentName && res.push(item.departmentName);
    item.duty && res.push(item.duty);
    item.rank && res.push(item.rank);
    return res.join(' - ');
  };

  handleSelectJob = job => {
    this.setState({
      jobId: job.key,
      departmentName: this.state.jobListObj[job.key].departmentName,
      companyName: this.state.jobListObj[job.key].companyName
    }, () => {
      this.getUser();
      this.getList();
    })
  };

  render() {
    const { user } = this.props;
    const { columns, userLoading, userInfo, data, tableLoading, departmentName, companyName,
      nowData, showSlideFrame, pagination, isOneMorePost, jobList } = this.state;
    let menu  = (
      <Menu onClick={this.handleSelectJob}>
        {jobList.map(job => {
          return <Menu.Item key={job.id}>{this.joinJob(job)}{job.companyMainPosition && ' (' + messages('components.key993')/*主岗*/ + ')'}</Menu.Item>
        })}
      </Menu>
    );
    return (
      <div className="reimbursement-credit">
        <div className="user-info">
          <span className="big-words">{user.fullName}</span>&nbsp;&nbsp;
          {messages('common.user.id')/*工号*/}：{user.employeeID}
          <span className="ant-divider"/>
          {messages('common.department')/*部门*/}：
          <Popover
            content={departmentName}
            overlayStyle={{maxWidth: 400}}
            placement="topLeft"
          >
            <span className="department-info">{departmentName}</span>
          </Popover>
          <span className="ant-divider"/> {messages('credit.key12')/*公司*/}：{companyName}
          {
            isOneMorePost &&
            <span className="change-job">
              <Dropdown overlay={menu}>
                <a className="ant-dropdown-link" href="#">
                  {messages('credit.key21')/*切换职位*/}
                  <Icon type="down"/>
                </a>
              </Dropdown>
            </span>
          }
        </div>
        <Spin spinning={userLoading}>
          <div>
            <div className="credit-info">
              <span className="big-words">{messages('credit.key13')/*信用分*/}</span>
              <b className="credit-number">{userInfo.score}</b>
              <If value={!!userInfo.creditRank}>
                <span className="big-words">{messages('credit.key14')/*信用等级*/}</span>
                <b className="credit-level">{userInfo.creditRank}</b>
              </If>
              <Condition>
                <If value={userInfo.creditStatus === 1001}>
                  <span className="credit-status no">{messages('credit.key15')/*未启用*/}</span>
                </If>
                <If value={userInfo.creditStatus === 1002}>
                  <span className="credit-status no">{messages('credit.key22')/*已失效*/}</span>
                </If>
                <If value={userInfo.creditStatus === 1003}>
                  <span className="credit-status">{messages('credit.key16')/*生效中*/}</span>
                </If>
              </Condition>
            </div>
            <If value={!!userInfo.creditRank}>
              <div className="credit-desc"> {messages('credit.key17')/*等级说明*/}：{userInfo.rankComment || '-'}
              </div>
            </If>
            <br/>
          </div>
        </Spin>
        <div className="transparent-bar"/>
        <div className="credit-title">
          <span className="big-words">{messages('credit.key18')/*信用事件*/}</span>
        </div>
        <div className="table-title">
          <RadioGroup defaultValue={undefined} onChange={this.handleChangeRadio}>
            <RadioButton value={undefined}>{messages('common.all')/*全部*/}</RadioButton>
            {constants.creditRuleOperation.map(item => <RadioButton value={item.value} key={item.value}>{item.text}</RadioButton>)}
          </RadioGroup>
        </div>
        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total',{total:`${pagination.total}`})}
          </div>
          <Search
            placeholder={messages('credit.key19')/*请输入单号*/}
            onChange={e => this.handleChangeBusinessCode(e.target.value)}
            className="credit-search"
          />
        </div>
        <ResizeTable
          columns={columns}
          loading={tableLoading}
          bordered
          rowKey="id"
          onRow={
            record => ({
              onClick: () => this.rowClick(record)
            })
          }
          pagination={pagination}
          size="middle"
          dataSource={data}
        />
        <SlideFrame
          show={showSlideFrame}
          content={EventDetail}
          onClose={() => this.setState({ showSlideFrame: false })}
          params={{ data: nowData }}
          title={messages('credit.key20')/*查看信用事件*/}
        />
      </div>
    )
  }
}

ReimbursementCredit.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user
  }
}

export default connect(mapStateToProps)(ReimbursementCredit)
